package com.fintech.pangu.upms.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fintech.pangu.upms.web.dao.SysUserTenantDao;
import com.fintech.pangu.upms.web.dto.SysUserTenantDto;
import com.fintech.pangu.upms.web.entity.SysUserTenant;
import com.fintech.pangu.upms.web.service.SysUserTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Admin
 * @since 2019-10-30
 */
@Service
public class SysUserTenantServiceImpl implements SysUserTenantService {

    @Autowired
    private SysUserTenantDao sysUserTenantDao;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUserTenant(SysUserTenantDto sysUserTenantDto) {
        // 先删后增
        QueryWrapper<SysUserTenant> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserTenant::getUserId,sysUserTenantDto.getUserId());
        sysUserTenantDao.delete(queryWrapper);

        Optional.ofNullable(sysUserTenantDto.getTenantIds())
                .ifPresent(list -> list.stream()
                        .forEach(tenantId ->{
                                    SysUserTenant sysUserTenant = new SysUserTenant();
                                    sysUserTenant.setUserId(sysUserTenantDto.getUserId());
                                    sysUserTenant.setTenantId(String.valueOf(tenantId));
                                    sysUserTenantDao.insert(sysUserTenant);
                            }
                        )
                );
    }
}
